"""
mqtt 
topic = "/xixiang/visioncook/jxsdc/post"
msg = {"plate_exit":1,"plate_empty":{"1":1,"2":1}}
发布餐盘信息{}
"""
import paho.mqtt.client as mqtt
import json,time
import threading
from configs import parse_args,logger
class MqttPub:

    def __init__(self) -> None:
        super().__init__()
        self.args = parse_args()
        self.client_id = self.args.mqtt_client_id #+"-"+str(uuid.uuid1())
        self.mqtt_host = self.args.mqtt_host
        self.mqtt_port = 1883
        self.mqtt_keepalive = 30
        self.mqtt_topic_palte_pub = self.args.mqtt_topic_palte_pub
        self.mqtt_topic_pot_pub = self.args.mqtt_topic_pot_pub
        self.topic_sub = ""
        self.username = self.args.mqtt_username
        self.password = self.args.mqtt_password
        self.client = mqtt.Client(client_id = self.client_id)
        # self.client.enable_logger()
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_message = self.on_message
        self.client.on_publish = self.on_publish
        self.client.on_subscribe = self.on_subscribe
        self.client.on_unsubscribe = self.on_unsubscribe
        # self.client.message_callback_add(subscribe_topic_running, self.on_running_message)#注册回调函数
        # self.client.message_callback_add(subscribe_topic_command, self.on_command_message)#注册回调函数
        self.client.username_pw_set(self.username, self.password)
        try:
            self.client.connect(self.mqtt_host, self.mqtt_port, self.mqtt_keepalive)
        except:
            print("程序连接服务器异常，请检测网络和配置")
        # self.client.loop_forever()

    # The callback for when the client receives a CONNACK response from the server.
    def on_connect(self,client, userdata, flags, rc):
        # print("Connected with result code "+str(rc))
        print("Connected with result code "+str(rc))
        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        # self.client.subscribe(self.topic_sub,qos=1)
        # self.client.subscribe(subscribe_topic_running)
        # self.client.subscribe(subscribe_topic_command)

    # The callback for when a PUBLISH message is received from the server.
    def on_message(self,client, userdata, msg):
        message = json.loads(msg.payload.decode('utf-8'))
        print(message)

    def on_running_message(self,client, userdata, msg):#自定义处理特定主题的回调函数
        print("on_running_message 主题:" + msg.topic + " 消息:" + str(msg.payload.decode('utf-8')))

    def on_command_message(self,client, userdata, msg):#自定义处理特定主题的回调函数
        print("on_command_message 主题:" + msg.topic + " 消息:" + str(msg.payload.decode('utf-8')))

    def on_publish(self,client, userdata, mid):
        # self.client.publish(topic=self.topic_pub, payload=json.dumps(base_order.WaringRecord.getParam()))
        # print("On onPublish: qos = %d" % (mid))
        # print("On onPublish: qos = {}".format(mid))
        pass

    def on_subscribe(self,client, userdata, mid, granted_qos):
        print("On Subscribed: qos = %d" % granted_qos)

    #   取消订阅回调
    def on_unsubscribe(self,client, userdata, mid, granted_qos):
        print("On unSubscribed: qos = %d" % granted_qos)

    #   断开链接回调
    def on_disconnect(self,client, userdata, rc):
        print("Unexpected disconnection rc = " + str(rc))
        print("程序连接服务器断开，请检测网络和ClientID")
        try:
            self.client.connect(self.mqtt_host, self.mqtt_port, self.mqtt_keepalive)
        except:
            print("程序连接服务器异常，请检测网络和配置")


    def pub(self,topic,msg:dict):
        print(msg)
        self.client.publish(topic=topic,payload=json.dumps(msg),qos=1)
if __name__ == "__main__":
    mqtt_host = "47.102.110.192"
    client_id = "dacaitai"
    mqtt_topic_palte_pub = "/xixiang/visioncook/55/plate/post"
    mqtt_topic_pot_pub = "/xixiang/visioncook/55/pot/post"
    msg_palte= {"plate_exist":1,"plate_empty":{"11":0,"12":0,"13":0,"22":0,"21":0}}
    mq = MqttPub()
    
    # msg_pot ={"pot_menu":{"11":"大骨汤面","12":"","21":"","22":"","31":"","32":""}}
    msg_pot ={"pot_menu":{"11":{"CLK124":"方腿毛豆"},"12":{"MDJ777":"素肠毛豆肉片"},"21":{"MDJ265":"韭菜鸡蛋"},"22":{"MDJ651":"茭白肉丝"},"31":{"MDJ001":"山药木耳肉片"},"32":{"MDJ867":"青豆玉米虾仁"}}}#
    # msg_pot ={"pot_menu":{"11":{"CLK124":"宫保鸡丁"},"12":{},"21":{},"22":{},"31":{},"32":{}}}#
    # msg_pot ={"pot_menu":{"11":"宫保鸡丁","12":"红肠玉米粒虾仁","21":"麻辣豆腐","22":"青椒肉丝","31":"丝瓜炒蛋","32":"鱼香鸭血"}}
    threading.Thread(target=mq.client.loop_forever).start()
    
    while True:
        time.sleep(6)
        # mq.pub(topic=mqtt_topic_palte_pub,msg=msg_palte)
        mq.pub(topic=mqtt_topic_pot_pub,msg=msg_pot)
    